package guoanmaker.provider.business.service;

import java.util.Date;
import java.util.List;

import java.util.HashMap;

import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;

import guoanmaker.provider.business.model.*;
import guoanmaker.provider.business.repository.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import guoanmaker.provider.business.modelnobind.ProvideOrderFormForOrder;
import guoanmaker.provider.business.modelnobind.ProviderBusinessMove;
import org.springframework.transaction.annotation.Isolation;

/**
 *
 * @author lhy
 *
 */

@Service
public class ProviderBusinessService implements ProviderBusinessServiceIntegerface {
	@Autowired
	private ProviderBusinessRepository providerBusinessRepository;
	@Autowired
	private ProvideCommodityRepository provideCommodityRepository;
	@Autowired
	private PersonalUserRepository personalUserRepository;
	@Autowired
	private ProviderBusinessServerRangeRepository serverRangeRepository;
	@Autowired
	private OperatorServerClassService serverClassService;
	@Autowired
	private ProvideShopServiceInterface provideShopService;
	@Autowired
	private ProvideShopRepository provideShopRepository;
	@PersistenceContext
	private EntityManager manager;


	@Override
	@Transactional
	public ProviderBusiness save(ProviderBusiness providerBusiness) {

        ProviderBusiness pb=	providerBusinessRepository.saveAndFlush(providerBusiness);
		ProvideShop shopTodelete = provideShopRepository.findShop(pb.getId());
		if (shopTodelete!=null) {
			provideShopRepository.delete(shopTodelete);
		}

		ProvideShop provideShop = new ProvideShop();

		provideShop.setProviderBusiness(pb);
		provideShop.setBusinessName(pb.getBusinessName());
		provideShop.setLicensPhone(pb.getLicensPhone());
		provideShop.setCompanyAdress(pb.getCompanyAdress());
		provideShop.setCompanyArea(pb.getCompanyArea());
		provideShop.setCompanyCity(pb.getCompanyCity());
        provideShop.setCompanyProvince(pb.getCompanyProvince());
        provideShop.setCompanyLogo(pb.getCompanyLogo());
        provideShop.setCompanyLicenseReplica(pb.getCompanyLicenseReplica());
        provideShop.setIntroduce(pb.getIntroduce());
        provideShop.setCreateTime(new Date());
        provideShop.setFollowNum(0L);
        provideShop.setState(0);
        provideShop.setStateTime(new Date());
		String id = pb.getId();
        //处理cal 省市区
		String sql = "select " +
				" concat(( select name from t_provide_province where code = a.company_province ),( select name from t_provide_city where code = a.company_city ),( select name from t_provide_area where code = a.company_area )) " +
				" from " +
				" t_provide_business a " +
				"where " +
				" a.id = '"+id+"'";
		Query nativeQuery = manager.createNativeQuery(sql);
		List resultList = nativeQuery.getResultList();
		provideShop.setCal(resultList.get(0).toString());
		ProvideShop save = provideShopRepository.saveAndFlush(provideShop);

		pb.setShopId(save.getId());
		providerBusinessRepository.saveAndFlush(pb);
		//更新下pb表的id
//		String sql = "update t_provide_business t set t.shop_id='" + shopId + "' where id='" + id + "'";
//		Query qry = manager.createNativeQuery(sql);
//		int i = qry.executeUpdate();

				/*if(pb!=null){
					PersonalUser personalUser=personalUserRepository.findOne(providerBusiness.getPersonalUser().getId());
					if(personalUser!=null){
					personalUser.setIsProvider("1");
					personalUserRepository.save(personalUser);}
					
				}*/

        return pb;

	}

	@Override
	public ProviderBusiness selectpro(String id) {
		ProviderBusiness   bus = providerBusinessRepository.findOne(id);
		return bus;
	}

	@Override
	public Integer delectbus(String id) {
		Integer comNum=0;
		comNum= provideCommodityRepository.selectCommidityNum(id);
		if(comNum==0){
			providerBusinessRepository.delete(id);
		}
		return comNum;

	}

	@Override
	public ProviderBusiness selectBusinessByUserid(String userid) {
		ProviderBusiness business=providerBusinessRepository.findBusiness(userid);
		return business;
	}

	//根据商户id修改商户服务范围
	@Override
	@Transactional
	public int updateBusinessCommdoity(ProviderBusinessServerRange providerBusinessServer) {
		String strc="";
		String busId=providerBusinessServer.getBusiness().getId();
		if(providerBusinessServer.getIns_commoditys()!=null && !providerBusinessServer.getIns_commoditys().equals("")){
			strc=",  p.service_range=1";
			String del="delete from ProviderBusinessServerRange p where p.business.id=:businessId";
			Query query = manager.createQuery(del);
			query.setParameter("businessId", busId);
			query.executeUpdate();
			serverRangeRepository.delete(providerBusinessServer);
			providerBusinessServer=serverRangeRepository.save(providerBusinessServer);
		}
		if(providerBusinessServer.getDel_commoditys()!=null  && !providerBusinessServer.getDel_commoditys().equals("")){
			String commodityService=providerBusinessServer.getDel_commoditys();
			String[] commoditySs=commodityService.split(",");
			Query query1 = null;
			for(int i=0;i<commoditySs.length;i++){
				String service_type_id=commoditySs[i];
				List<String> serverIds=serverClassService.getServerIdByParentServerId(service_type_id);
				String str=getServiceType(serverIds);
				String hql="update t_provide_Commodity t set t.commodity_state=6 where t.business_id='"+busId+"'"+" and t.service_type_id in ("+str+")";
				query1 = manager.createNativeQuery(hql);
				query1.executeUpdate();
			}
		}
		List<OperatorServerClass> serverClasss=serverClassService.selectByIdAndServerType(providerBusinessServer.getSpare_commoditys(), 1);
		Integer serverType=2;
		if(serverClasss!=null){
			if(serverClasss.size()>0){
				serverType=1;
			}
		}
		String jpql = "UPDATE ProviderBusiness p set p.commoditys=:commoditys "+strc+", p.isRoomServer=:isRoomServer , p.new_commoditys=:new_commoditys  where p.id =:id";
		Query query = manager.createQuery(jpql);
		String businessId=providerBusinessServer.getBusiness().getId();
		query.setParameter("id",businessId);
		query.setParameter("commoditys", providerBusinessServer.getSpare_commoditys());
		query.setParameter("new_commoditys", providerBusinessServer.getNew_commoditys());
		query.setParameter("isRoomServer", serverType);
		int reuslt=query.executeUpdate();
		String sql = "update t_provide_business set range_mod_time=now() where id='"+businessId+"'";
		int i = manager.createNativeQuery(sql).executeUpdate();
		return reuslt;
	}

	/**
	 * 获取服务类型id串
	 * @author baixsh
	 * @param  ids(类型主键集合)
	 * */
	public static String getServiceType(List<String> ids){
		String str="";
		if(ids!=null){
			for(int k=0;k<ids.size();k++){
				if(k==0){
					str=str+"'"+ids.get(k)+"'";
				}else{
					str=str+",'"+ids.get(k)+"'";
				}
			}
		}
		return str;
	}
	@Override
	public Map<String,Object> selectBusinessById(String businessId) {
		Map<String,Object> map=new HashMap<String,Object>();
		//查询商家管理中心首页的商家信息
		String jpql="select new guoanmaker.provider.business.modelnobind.ProviderBusinessMove(pu.businessName,pu.companyLogo,user.username,user.lastLandTime) from ProviderBusiness "
				+ "pu left join pu.personalUser user where pu.id=:businessId";
		Query query=manager.createQuery(jpql);
		query.setParameter("businessId", businessId);
		List<ProviderBusinessMove> list=query.getResultList();
		map.put("businessItem", list);
		query=null;
		//查询商家管理中心首页的发布商品数量
		String jpql1="select new guoanmaker.provider.business.modelnobind.dataStatisticsMove(pc.commodityState,count(1)) from ProviderBusiness "
				+ "pu left join pu.ProvideCommodity pc where pu.id=:businessId group by pc.commodityState";
		Query query1=manager.createQuery(jpql1);
		query1.setParameter("businessId", businessId);
		List<ProvideOrderFormForOrder> list1=query1.getResultList();
		map.put("commodityCount", list1);
		query1=null;
		//查询商家管理中心首页的交易订单
		String jpql2="select new guoanmaker.provider.business.modelnobind.dataStatisticsMove(orf.orderStatus,count(1)) from ProviderBusiness "
				+ "pu left join pu.ProvideCommodity pc right join pc.orderforms orf where pu.id=:businessId group by orf.orderStatus";
		Query query2=manager.createQuery(jpql2);
		query2.setParameter("businessId", businessId);
		query2.getResultList();
		List<ProvideOrderFormForOrder> list2=query2.getResultList();
		map.put("orderFormCount", list2);
		query2=null;
		//查询商家管理中心首页的昨日订单数量与订单金额
		String jpql3="select new guoanmaker.provider.business.modelnobind.dataStatisticsMove(count(1),SUM(po.realPrice)) from ProvideOrderForm "
				+ "po left join po.commodity pc left join pc.providerBusiness pb where pb.id=:businessId and TO_DAYS(NOW( ))-"
				+ "TO_DAYS(po.placeOrderTime) = 1 and po.orderStatus in (6,8,12,13)";
		Query query3=manager.createQuery(jpql3);
		query3.setParameter("businessId", businessId);
		List<ProvideOrderFormForOrder> list3=query3.getResultList();
		map.put("OrderYesterday", list3);
		query3=null;
		/*//查询商家管理中心首页的昨日的订单金额
		String jpql4="select new guoanmaker.provider.business.modelnobind.dataStatisticsMove(SUM(orf.realPrice)) from ProviderBusiness "
				+ "pu left join pu.ProvideCommodity pc right join pc.orderforms orf where pu.id=:businessId and orf.orderStatus=6 and TO_DAYS(NOW( ))-TO_DAYS(orf.placeOrderTime) <= 1";
		Query query4=manager.createQuery(jpql4);
		query4.setParameter("businessId", businessId);
		List<ProvideOrderFormForOrder> list4=query4.getResultList();
		map.put("OrderAmountYesterday", list4);
		query4=null;*/
		//查询商家管理中心首页的当月订单数量与订单金额
		String jpql5="select new guoanmaker.provider.business.modelnobind.dataStatisticsMove(count(1),SUM(po.realPrice)) from ProvideOrderForm "
				+ "po left join po.commodity pc left join pc.providerBusiness pb where pb.id=:businessId and date_format(po.placeOrderTime,'%Y%m') "
				+ "= date_format(curdate(),'%Y%m') and po.orderStatus in (6,8,12,13)";
		Query query5=manager.createQuery(jpql5);
		query5.setParameter("businessId", businessId);
		List<ProvideOrderFormForOrder> list5=query5.getResultList();
		map.put("OrderForTheMonth", list5);
		query5=null;
		/*//查询商家管理中心首页的当月的订单金额
		String jpql6="select new guoanmaker.provider.business.modelnobind.dataStatisticsMove(SUM(orf.realPrice)) from ProviderBusiness "
				+ "pu left join pu.ProvideCommodity pc right join pc.orderforms orf where pu.id=:businessId and orf.orderStatus=6 and date_format(orf.placeOrderTime,'%Y%m') = date_format(curdate(),'%Y%m')";
		Query query6=manager.createQuery(jpql6);
		query6.setParameter("businessId", businessId);
		List<ProvideOrderFormForOrder> list6=query6.getResultList();
		map.put("OrderAmountForThatMonth", list6);
		query6=null;*/
		return map;

	}

}
